package com.vdong.common.oauth.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.config.AuthorizerApiConfig;
import com.github.sd4324530.fastweixin.api.enums.ResultType;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.TextReqMsg;
import com.github.sd4324530.fastweixin.message.req.WeAppAuditEvent;
import com.vdong.common.oauth.common.util.AbstractOpenPlatformSupport;
import com.vdong.common.oauth.service.WechatAuthorizerInfoService;
import com.vdong.common.oauth.service.WechatConfigService;
import com.vdong.common.oauth.service.WechatService;
import com.vdongchina.boot.wechat.util.WechatUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class WeixinService extends AbstractOpenPlatformSupport {
    private static Logger logger = LoggerFactory.getLogger(WeixinService.class);

    @Autowired
    private OauthDynamicPropertyService oauthDynamicPropertyService;

    //private String token = oauthDynamicPropertyService.getToken();

    //private String appid = oauthDynamicPropertyService.getAppid();

    //private String secret = oauthDynamicPropertyService.getSecret();

    //private String key = oauthDynamicPropertyService.getKey();

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private WechatConfigService wechatConfigService;
    @Resource
    private WechatAuthorizerInfoService wechatAuthorizerInfoService;
    @Resource
    private WechatService wechatService;


    @Override
    protected RedisTemplate getRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(redisTemplate.getConnectionFactory());
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
        template.setHashKeySerializer(jdkSerializationRedisSerializer);
        template.setValueSerializer(jdkSerializationRedisSerializer);
        return template;
    }

    @Override
    protected String getToken() {
        return oauthDynamicPropertyService.getToken();
    }

    @Override
    protected String getAppId() {
        return oauthDynamicPropertyService.getAppid();
    }

    @Override
    protected String getAESKey() {
        return oauthDynamicPropertyService.getKey();
    }

    @Override
    protected String getSecret() {
        return oauthDynamicPropertyService.getSecret();
    }

    public void processNotify(String msg_signature, String timestamp, String nonce, HttpServletRequest request) {
        logger.info("第三方token:" + oauthDynamicPropertyService.getToken() + "第三方appid:" + oauthDynamicPropertyService.getAppid()
                + "第三方Secret:" + oauthDynamicPropertyService.getSecret() + "第三方Key:" + oauthDynamicPropertyService.getKey());
        if (!isLegal(request)) {
            return;
        }
        String postData = "";
        try {
            postData = IOUtils.toString(request.getInputStream(), "utf-8");
            logger.info("~~~~~~~~~~~~~~~~~~~~~~~~postDate~~" + postData + "~~~~~~~~~~~~~~~~~~~~~~~~~");
        } catch (Exception e) {
            e.printStackTrace();
        }
        test(msg_signature, timestamp, nonce, postData);
        //this.notifyReceive(msg_signature, timestamp, nonce, request);
    }

    public void test(String msg_signature, String timestamp, String nonce, String postData) {
        try {
            postData = this.getMsgCrypt().decryptAuth(msg_signature, timestamp, nonce, postData);
            org.dom4j.Document doc = DocumentHelper.parseText(postData);
            org.dom4j.Element rootElt = doc.getRootElement();
            String infoType = rootElt.elementText("InfoType");
            logger.info("~~~~~~~~~~~~~~~~~~~~~~~~infoType~~~~~~~~~~~~" + infoType + "~~~~~~~~~~~~~~~~~~~~~~~~~");
            if (StringUtils.isBlank(infoType)) {
                return;
            }

            String componentVerifyTicket = "component_verify_ticket";
            String authorized = "authorized";
            String updateAuthorized = "updateauthorized";
            String unauthorized = "unauthorized";

            if (componentVerifyTicket.equals(infoType)) {
                String ticket = rootElt.elementText("ComponentVerifyTicket");
                this.getRedisTemplate().opsForValue().set("fx_wxTicket", ticket);
                logger.debug("------------ticket~~~~~~~~~~~~~~~~~~~~~~~~：" + ticket);
                this.getTicket(ticket);
            } else if (authorized.equals(infoType)) {
                this.authorized(rootElt.elementText("AuthorizerAppid"), rootElt.elementText("AuthorizationCode"));
            } else if (updateAuthorized.equals(infoType)) {
                this.updateAuthorized(rootElt.elementText("AuthorizerAppid"), rootElt.elementText("AuthorizationCode"));
            } else if (unauthorized.equals(infoType)) {
                this.unAuthorized(rootElt.elementText("AuthorizerAppid"));
            }
        } catch (Exception var10) {
            var10.printStackTrace();
        }

    }

    public String processMessage(HttpServletRequest request, String appid) {
        if (!isLegal(request)) {
            return "";
        }
        return processRequest(request, appid);
    }

    @Override
    protected void getTicket(String ticket) {
        logger.debug("接收微信推送消息:wxTicket:{}", ticket);
        super.getTicket(ticket);
    }

    @Override
    protected BaseMsg handleWeAppAuditEvent(WeAppAuditEvent event) {
        if (event == null) {
            return null;
        }
        logger.debug("小程序审核代码结果:{}", event.toString());
        wechatService.updateAuditResult(event.getAppid(), event.getResult(), event.getReason());
        return null;
    }

    @Override
    protected void authorized(String appId, String code) {
        // 回调已经处理授权信息保存，这里就不处理了
        // wechatAuthorizerInfoService.saveAuthorizerInfo(appId, code);
        logger.debug("authorized 绑定授权 appId;{},code;{}", appId, code);
        //wechatAuthorizerInfoService.saveAuthInfo(appId, code);
    }

    @Override
    protected void updateAuthorized(String appid, String code) {
        logger.debug("updateAuthorized 更新授权 appId;{},code;{}", appid, code);
        //wechatAuthorizerInfoService.saveAuthInfo(appid, code);
        //wechatAuthorizerInfoService.saveAuthInfo(appid, code);
    }

    @Override
    protected void unAuthorized(String appid) {
        logger.debug("unAuthorized 取消授权 appId;{}", appid);
        wechatAuthorizerInfoService.unauthorized(appid);
    }

    @Override
    protected BaseMsg handleTextMsg(TextReqMsg msg) {
        String msgContent = msg.getContent();
        logger.debug("测试消息:{}", msgContent);
        //接入检测
        String text = "TESTCOMPONENT_MSG_TYPE_TEXT";
        if (text.equals(msgContent)) {
            String newContent = "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
            TextMsg textMsg = new TextMsg(newContent);
            return textMsg;
            /*String appId = "wx570bc396a51b8ff8";
            WechatAuthorizerInfo info = wechatAuthorizerInfoService.loadByAppid(appId);
            AuthorizerApiConfig config = getAuthorizerApiConfig(appId, info.getRefreshToken());
            CustomAPI api = new CustomAPI(config);
            //MessageAPI api = new MessageAPI(config);
            ResultType resultType = api.sendCustomMessage(msg.getFromUserName(), textMsg);
            // api.sendMessageToUser(null,false,1);
            logger.debug("===========消息回复结果:{}", resultType.getDescription());
            return textMsg;*/
        }
        String code = "QUERY_AUTH_CODE";
        if (StringUtils.isNotEmpty(msgContent) && msgContent.contains(code)) {

            String queryAuthCode = StringUtils.split(msgContent, ":")[1];
            logger.debug("query_auth_code:{}" + queryAuthCode);
            //String appId = "wxd101a85aa106f53e";
            String appId = "wx570bc396a51b8ff8";
            String username = "gh_8dad206e9538";

            String acctoken = super.getComponentApiConfig().getAccessToken();
            JSONObject aujson = WechatUtil.getQueryAuth(getAppId(), queryAuthCode, acctoken);
            logger.debug("测试消息，获取到授权信息:{}" + aujson);
            JSONObject authorizationInfo = aujson.getJSONObject("authorization_info");
            //String authorizerAppid = authorization_info.getString("authorizer_appid");
            String refreshToken = authorizationInfo.getString("authorizer_refresh_token");
            logger.debug("测试消息，refreshToken:{}" + refreshToken);
            //JSONObject json = WechatUtil.getAuthorizerInfo(getAppId(), appId, super.getComponentApiConfig().getAccessToken());
            String newContent = queryAuthCode + "_from_api";
            TextMsg textMsg = new TextMsg(newContent);

            AuthorizerApiConfig config = getAuthorizerApiConfig(appId, refreshToken);
            CustomAPI api = new CustomAPI(config);
            //MessageAPI api = new MessageAPI(config);
            ResultType resultType = api.sendCustomMessage(msg.getFromUserName(), textMsg);
            // api.sendMessageToUser(null,false,1);
            logger.debug("===========消息回复结果:{}", resultType.getDescription());
            return new TextMsg("");
        }

        //用户购买 课程自动回复
//        if ("1".equals(msgContent)) {
//            String appId = msg.getAppid();
//            String openId = msg.getFromUserName();
//            WechatAuthorizerInfo info = wechatAuthorizerInfoService.loadByAppid(appId);
//            AuthorizerApiConfig config = getAuthorizerApiConfig(appId, info.getRefreshToken());
//            CustomAPI api = new CustomAPI(config);
//
//            TextMsg textMsg = wechatOrderService.createBuyUrl(openId);
//            if (textMsg != null) {
//                ResultType resultType = api.sendCustomMessage(msg.getFromUserName(), textMsg);
//                //api.sendMessageToUser(null,false,1);
//                logger.debug("===========消息回复结果:" + resultType.getDescription());
//            }
//            return textMsg;
//        }
        return null;

    }
}